package br.com.firula.util;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class ImagemUtils {
	
	public static boolean redimensionaSaveImg(BufferedImage img_orig, String ext, String caminho) {
		try {
			BufferedImage img = img_orig;
			
			int largura = -1;
			int altura = -1;
			
			Integer widthAux = 600;
			Integer heightAux = 600;
			
			String width = widthAux.toString();
			String height = heightAux.toString();
			
			double l_orig = img_orig.getWidth();
			double a_orig = img_orig.getHeight();
			
			if ( (l_orig > widthAux) || (a_orig > heightAux) ) { 
				largura = Integer.parseInt(width);
				altura = Integer.parseInt(height);
				
				double prop1 = l_orig / (double)largura;
				double prop2 = a_orig / (double)altura;
				
				
				if (prop1 > prop2){
					altura = (int)(a_orig / prop1);
					largura = (int)(l_orig / prop1);
				} else {
					altura = (int)(a_orig / prop2);
					largura = (int)(l_orig / prop2);
				}
			
				if (width != null && height != null) {
					Image novaImagem = img_orig.getScaledInstance(largura,altura, Image.SCALE_SMOOTH);
					BufferedImage bimage = new BufferedImage(largura, altura, BufferedImage.TYPE_INT_RGB);
						
					Graphics2D g = bimage.createGraphics();
					g.drawImage(novaImagem, 0, 0, null);
					g.dispose();
					img = bimage;
				}
			}	
			ImageIO.write(img, ext, new File(caminho));
			
			return true;
		} catch(Exception e) {
			e.printStackTrace();
			return false;
		}		
	}
}